<%--
  Created by IntelliJ IDEA.
  User: 欧阳佳新
  Date: 2025/1/2
  Time: 14:36
  To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的订单</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
            font-family: Arial, Helvetica, sans-serif;
        }
        .container {
            margin-top: 20px;
        }
        .table thead {
            background-color: #f1f1f1;
        }
        .btn-action {
            font-size: 14px;
            padding: 5px 10px;
        }
        .btn-action:hover {
            opacity: 0.8;
        }
    </style>
</head>
<body>
<div class="container">
    <h1 class="mb-4">我的订单</h1>

    <!-- 订单表格 -->
    <table class="table table-bordered">
        <thead>
        <tr>
            <th>订单ID</th>
            <th>总价</th>
            <th>订单状态</th>
            <th>操作</th>
            <th>订单详情</th> <!-- 新增的订单详情列 -->
        </tr>
        </thead>
        <tbody>
        <c:if test="${not empty orders}">
            <c:forEach var="order" items="${orders}">
                <tr>
                    <td>${order.orderId}</td>
                    <td>¥${order.totalPrice}</td>
                    <td>${order.status}</td>

                    <td>
                        <c:choose>
                            <c:when test="${order.status == '已提交'}">
                                <a href="javascript:void(0);" class="btn btn-danger btn-action" onclick="cancelOrder(${order.orderId})">取消订单</a>
                            </c:when>
                            <c:when test="${order.status == '已发货'}">
                                <a href="javascript:void(0);" class="btn btn-success btn-action" onclick="confirmReceipt(${order.orderId})">确认收货</a>
                            </c:when>
                            <c:when test="${order.status == '已收货'}">
                                <a href="javascript:void(0);" class="btn btn-success btn-action" onclick="fetchOrderDetailsForReview(${order.orderId})">前往评价</a>
                            </c:when>
                            <c:otherwise>
                                <span class="text-muted">无操作</span>
                            </c:otherwise>
                        </c:choose>
                    </td>

                    <!-- 显示订单详情信息 -->
                    <td>
                        <button class="btn btn-info btn-action" onclick="showOrderDetails(${order.orderId})">查看详情</button>
                    </td>
                </tr>
            </c:forEach>
        </c:if>
        <c:if test="${empty orders}">
            <tr>
                <td colspan="5" class="text-center">没有找到订单</td>
            </tr>
        </c:if>
        </tbody>
    </table>

</div>
<!-- 评价模态框 -->
<div class="modal fade" id="reviewModal" tabindex="-1" aria-labelledby="reviewModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="reviewModalLabel">评价订单</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
            </div>
            <div class="modal-body">
                <div id="reviewContent">
                    <!-- 动态加载的商品评价表单 -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="submitreview"onclick="submitReview()">提交评价</button>
            </div>
        </div>
    </div>
</div>


<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    function cancelOrder(orderId) {
    if (!orderId) {
        alert("订单 ID 无效");
        return;
    }
        var xhr = new XMLHttpRequest();
        xhr.open('DELETE', 'OrderServlet?orderId=' + orderId + '&action=cancel', true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    alert("订单已成功取消！");
                    window.location.reload();
                } else {
                    alert("取消订单失败！");
                }
            }
        };
        xhr.send();
    }

    function confirmReceipt(orderId) {
        var xhr = new XMLHttpRequest();
        xhr.open('PUT', 'OrderServlet?orderId=' + orderId+ '&action=receive', true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    var response = JSON.parse(xhr.responseText);
                    if (response.status === "success") {
                        alert(response.message);
                        window.location.reload();
                    } else {
                        alert(response.message);
                    }
                } else {
                    alert("确认收货失败，请稍后再试！");
                }
            }
        };
        xhr.send();
    }

    function showOrderDetails(orderId) {
    // 使用 XMLHttpRequest 异步请求订单详情
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'OrderDetailsServlet?orderId=' + orderId, true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                try {
                    // 假设服务器返回的是 JSON 格式的订单详情
                    var data = JSON.parse(xhr.responseText);
                    if (Array.isArray(data)) {
                        // 将订单详情拼接成字符串并通过 alert 显示
                        var details = '';
                        for (var i = 0; i < data.length; i++) {
                            var item = data[i];
                            details += '商品名称: ' + item.name + '\n';
                            details += '单价: ¥' + item.price.toFixed(2) + '\n';
                            details += '数量: ' + item.quantity + '\n\n';
                        }
                        alert('订单详情:\n\n' + details);
                    } else {
                        alert('未找到订单详情。');
                    }
                } catch (e) {
                    alert('订单详情解析错误！');
                }
            } else {
                alert('无法加载订单详情，请稍后再试！');
            }
        }
    };
    xhr.send();
}
    function fetchOrderDetailsForReview(orderId) {
    if (!orderId) {
        alert("订单 ID 无效");
        return;
    }

    // 异步请求订单详情
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'OrderDetailsServlet?orderId=' + orderId, true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                try {
                    var orderDetails = JSON.parse(xhr.responseText); // 假设返回 JSON 格式数据
                    if (Array.isArray(orderDetails)) {
                        // 动态生成商品评价表单
                        generateReviewForm(orderDetails);
                        // 显示模态框
                        var reviewModal = new bootstrap.Modal(document.getElementById('reviewModal'));
                        reviewModal.show();
                        document.getElementById('submitreview').setAttribute('onclick', 'submitReview(' + orderId + ')');
                    } else {
                        alert("未找到订单详情！");
                    }
                } catch (e) {
                    console.error("订单详情解析错误", e);
                    alert("加载订单详情失败！");
                }
            } else {
                alert("无法加载订单详情，请稍后再试！");
            }
        }
    };
    xhr.send();
}

function generateReviewForm(orderDetails) {
    var reviewContent = document.getElementById('reviewContent');
    reviewContent.innerHTML = ''; // 清空现有内容

    orderDetails.forEach((item, index) => {
        var formItem = `
            <div class="mb-3">
                <h6>商品名称: `+ item.name + `</h6>
                <p>单价: ¥`+ item.price.toFixed(2) +`</p>
                <p>数量: `+ item.quantity +`</p>
                <textarea class="form-control" rows="3" id="reviewText`+index+`" placeholder="填写您的评价..." data-product-id=` + item.productId + `></textarea>
                <hr>
            </div>
        `;
        reviewContent.innerHTML += formItem;
    });
}
function submitReview(orderId) {
    var reviewContent = document.getElementById('reviewContent');
    var items = reviewContent.querySelectorAll('.mb-3');

    var reviews = [];
    items.forEach((item, index) => {
        var reviewText = document.getElementById('reviewText' + index).value.trim();
        var productId = document.getElementById('reviewText' + index).getAttribute('data-product-id');
        reviews.push({
            productId: productId,
            reviewText: reviewText,
        });
    });

    // 构造 POST 请求发送数据
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'ReviewServlet?orderId=' + orderId, true);
    xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                alert("评价提交成功！");
                var reviewModal = bootstrap.Modal.getInstance(document.getElementById('reviewModal'));
                reviewModal.hide();
                window.location.reload();
            } else {
                alert("评价提交失败，请稍后再试！");
            }
        }
    };
    xhr.send(JSON.stringify(reviews));
}


</script>
</body>
</html>
